#!/usr/bin/env node

/**
 * iOS 礼券配置导入脚本
 * 从 CouponConfig.swift 解析优惠券数据并同步到后端数据库
 * 
 * 执行方式: npm run import:ios-coupons
 * 或: node scripts/import-ios-coupons.js
 * 
 * 特性:
 * - 幂等性安全（可重复执行）
 * - 支持 CouponConfig.swift 复杂解锁条件映射
 * - 自动创建时间段限制记录
 * - 保留现有优惠券数据完整性
 */

const { pool, testConnection } = require('../backend/src/config/database');
const fs = require('fs').promises;
const path = require('path');

class IOSCouponImporter {
  constructor() {
    this.couponConfigPath = path.join(__dirname, '../CMB250716/Config/CouponConfig.swift');
    this.importedCount = 0;
    this.updatedCount = 0;
    this.skippedCount = 0;
    
    // iOS 解锁条件类型映射到后端枚举
    this.unlockTypeMapping = {
      'none': 'always_available',
      'loginRequired': 'registration_completion',
      'membershipLevel': 'engagement_reward',
      'memberInfoComplete': 'profile_completion',
      'birthdayMonthRequired': 'birthday_special',
      'activationConditions': 'challenge_completion',
      'timeSlotRestricted': 'time_based',
      'usageLimitReached': 'always_available',
      'usageFrequencyReached': 'always_available',
      'expired': 'always_available',
      'inactive': 'always_available'
    };
    
    // iOS 折扣类型映射
    this.discountTypeMapping = {
      'fixedAmount': 'fixed_amount',
      'percentage': 'percentage',
      'freeItem': 'fixed_amount' // 免费商品按固定金额处理
    };
    
    // 会员等级映射
    this.membershipLevelMapping = {
      'Vibe Regent': 'platinum',
      'Aureus Legend': 'diamond',
      'Hype Blaze': 'gold',
      'Neon Rookie': 'silver'
    };
  }

  async run() {
    console.log('🚀 开始导入 iOS 礼券配置...\n');
    
    try {
      // 检查数据库连接
      const isConnected = await testConnection();
      if (!isConnected) {
        throw new Error('数据库连接失败，请检查配置');
      }

      // 检查配置文件是否存在
      await this.validateConfigFile();
      
      // 解析 iOS 配置文件
      const coupons = await this.parseIOSCoupons();
      console.log(`📝 解析到 ${coupons.length} 个 iOS 优惠券配置\n`);
      
      // 导入优惠券到数据库
      await this.importCoupons(coupons);
      
      // 显示导入结果
      this.displayImportSummary();
      
    } catch (error) {
      console.error('❌ 导入失败:', error.message);
      process.exit(1);
    }
  }

  /**
   * 验证配置文件存在
   */
  async validateConfigFile() {
    try {
      await fs.access(this.couponConfigPath);
      console.log(`✓ 找到配置文件: ${this.couponConfigPath}`);
    } catch (error) {
      throw new Error(`CouponConfig.swift 文件不存在: ${this.couponConfigPath}`);
    }
  }

  /**
   * 解析 iOS CouponConfig.swift 文件
   */
  async parseIOSCoupons() {
    const content = await fs.readFile(this.couponConfigPath, 'utf-8');
    const coupons = [];
    
    // 使用正则匹配 CouponData 结构
    const couponPattern = /CouponData\s*\(\s*([^)]+)\s*\)/gs;
    const matches = content.matchAll(couponPattern);
    
    for (const match of matches) {
      const couponDataString = match[1];
      const coupon = this.parseSingleCoupon(couponDataString);
      if (coupon) {
        coupons.push(coupon);
      }
    }
    
    return coupons;
  }

  /**
   * 解析单个优惠券配置
   */
  parseSingleCoupon(dataString) {
    try {
      const coupon = {};
      
      // 提取基础信息
      coupon.code = this.extractValue(dataString, 'code');
      coupon.title = this.extractValue(dataString, 'title');
      coupon.englishTitle = this.extractValue(dataString, 'englishTitle');
      coupon.description = this.extractValue(dataString, 'description');
      coupon.englishDescription = this.extractValue(dataString, 'englishDescription');
      
      // 提取折扣信息
      const discountType = this.extractEnumValue(dataString, 'discountType');
      coupon.type = this.discountTypeMapping[discountType] || 'fixed_amount';
      coupon.value = parseFloat(this.extractValue(dataString, 'discountValue')) || 0;
      coupon.min_order_amount = parseFloat(this.extractValue(dataString, 'minimumSpend')) || 0;
      
      // 提取有效期和限制
      coupon.validDays = parseInt(this.extractValue(dataString, 'validDays')) || 30;
      coupon.is_active = this.extractValue(dataString, 'isActive') === 'true';
      
      const usageLimit = this.extractValue(dataString, 'usageLimit');
      coupon.usage_limit_per_user = usageLimit === 'nil' ? null : parseInt(usageLimit);
      
      // 提取解锁条件
      coupon.requiresLogin = this.extractValue(dataString, 'requiresLogin') === 'true';
      
      const membershipLevel = this.extractValue(dataString, 'requiresMembershipLevel');
      if (membershipLevel && membershipLevel !== 'nil') {
        coupon.required_membership_level = this.membershipLevelMapping[membershipLevel] || 'bronze';
      }
      
      // 提取激活条件
      coupon.activationConditions = this.extractValue(dataString, 'activationConditions');
      coupon.englishActivationConditions = this.extractValue(dataString, 'englishActivationConditions');
      
      // 提取时间段信息
      coupon.timeSlots = this.extractTimeSlots(dataString);
      
      // 提取使用频率
      const usageFrequency = this.extractEnumValue(dataString, 'usageFrequency');
      coupon.usageFrequency = usageFrequency || 'once';
      
      // 设置解锁条件类型
      coupon.unlock_condition_type = this.determineUnlockConditionType(coupon);
      coupon.unlock_condition_config = this.buildUnlockConfig(coupon);
      
      return coupon;
    } catch (error) {
      console.warn('⚠️  解析优惠券时出现错误:', error.message);
      return null;
    }
  }

  /**
   * 提取字符串值
   */
  extractValue(dataString, key) {
    const pattern = new RegExp(`${key}:\\s*"([^"]*)"`, 'g');
    const match = pattern.exec(dataString);
    return match ? match[1] : null;
  }

  /**
   * 提取枚举值
   */
  extractEnumValue(dataString, key) {
    const pattern = new RegExp(`${key}:\\s*[^.,]+\\.([^,\\s)]+)`, 'g');
    const match = pattern.exec(dataString);
    return match ? match[1] : null;
  }

  /**
   * 提取时间段配置
   */
  extractTimeSlots(dataString) {
    const timeSlots = [];
    const timeSlotsPattern = /timeSlots:\s*\[([^\]]+)\]/;
    const match = timeSlotsPattern.exec(dataString);
    
    if (!match) return [];
    
    const timeSlotsStr = match[1];
    const slotPattern = /TimeSlotData\s*\(\s*weekdays:\s*\[([^\]]+)\],\s*startTime:\s*(\d+),\s*endTime:\s*(\d+)\s*\)/g;
    
    let slotMatch;
    while ((slotMatch = slotPattern.exec(timeSlotsStr)) !== null) {
      const weekdays = slotMatch[1].split(',').map(w => parseInt(w.trim()));
      const startTime = parseInt(slotMatch[2]);
      const endTime = parseInt(slotMatch[3]);
      
      // 将 iOS 的星期数字映射到后端格式
      for (const weekday of weekdays) {
        // iOS: 1=周日, 2=周一...7=周六
        // DB: 0=周日, 1=周一...6=周六
        const mysqlWeekday = (weekday - 1 + 7) % 7;
        
        timeSlots.push({
          day_of_week: mysqlWeekday,
          start_time: this.minutesToTime(startTime),
          end_time: this.minutesToTime(endTime)
        });
      }
    }
    
    return timeSlots;
  }

  /**
   * 将分钟数转换为时间格式
   */
  minutesToTime(minutes) {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return `${hours.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:00`;
  }

  /**
   * 根据优惠券信息确定解锁条件类型
   */
  determineUnlockConditionType(coupon) {
    if (coupon.code === 'BIRTHDAY30') {
      return 'birthday_special';
    }
    
    if (coupon.code === 'MEMBER_INFO_COMPLETE') {
      return 'profile_completion';
    }
    
    if (coupon.required_membership_level && coupon.required_membership_level !== 'bronze') {
      return 'engagement_reward';
    }
    
    if (coupon.activationConditions && coupon.activationConditions.includes('购买')) {
      return 'challenge_completion';
    }
    
    if (coupon.activationConditions && coupon.activationConditions.includes('周')) {
      return 'challenge_completion';
    }
    
    if (coupon.timeSlots && coupon.timeSlots.length > 0) {
      return 'time_based';
    }
    
    if (coupon.requiresLogin) {
      return 'registration_completion';
    }
    
    return 'always_available';
  }

  /**
   * 构建解锁条件配置
   */
  buildUnlockConfig(coupon) {
    const config = {
      description: coupon.activationConditions || '无限制条件',
      description_en: coupon.englishActivationConditions || 'No restrictions'
    };
    
    if (coupon.required_membership_level) {
      config.required_membership_level = coupon.required_membership_level;
    }
    
    if (coupon.usageFrequency) {
      config.usage_frequency = coupon.usageFrequency;
    }
    
    return JSON.stringify(config);
  }

  /**
   * 导入优惠券到数据库
   */
  async importCoupons(coupons) {
    console.log('📦 开始导入优惠券到数据库...\n');
    
    for (const coupon of coupons) {
      try {
        await this.importSingleCoupon(coupon);
      } catch (error) {
        console.error(`❌ 导入优惠券 ${coupon.code} 失败:`, error.message);
      }
    }
  }

  /**
   * 导入单个优惠券
   */
  async importSingleCoupon(coupon) {
    // 检查优惠券是否已存在
    const [existing] = await pool.execute(
      'SELECT id, updated_at FROM coupons WHERE code = ?',
      [coupon.code]
    );

    const currentTime = new Date();
    const endDate = new Date(currentTime.getTime() + coupon.validDays * 24 * 60 * 60 * 1000);

    if (existing.length > 0) {
      // 更新现有优惠券
      await this.updateExistingCoupon(existing[0].id, coupon, endDate);
      this.updatedCount++;
    } else {
      // 创建新优惠券
      await this.createNewCoupon(coupon, currentTime, endDate);
      this.importedCount++;
    }
  }

  /**
   * 更新现有优惠券
   */
  async updateExistingCoupon(couponId, coupon, endDate) {
    const updateSql = `
      UPDATE coupons SET 
        name = ?, name_en = ?, description = ?, description_en = ?,
        type = ?, value = ?, min_order_amount = ?,
        usage_limit_per_user = ?, is_active = ?, end_date = ?,
        unlock_condition_type = ?, unlock_condition_config = ?,
        ios_coupon_id = ?, required_membership_level = ?,
        updated_at = CURRENT_TIMESTAMP
      WHERE id = ?
    `;

    await pool.execute(updateSql, [
      coupon.title, coupon.englishTitle, coupon.description, coupon.englishDescription,
      coupon.type, coupon.value, coupon.min_order_amount,
      coupon.usage_limit_per_user, coupon.is_active, endDate,
      coupon.unlock_condition_type, coupon.unlock_condition_config,
      coupon.code, coupon.required_membership_level,
      couponId
    ]);

    // 更新时间段配置
    await this.updateTimeSlots(couponId, coupon.timeSlots);
    
    console.log(`✓ 已更新优惠券: ${coupon.code} (${coupon.title})`);
  }

  /**
   * 创建新优惠券
   */
  async createNewCoupon(coupon, startDate, endDate) {
    const insertSql = `
      INSERT INTO coupons (
        code, name, name_en, description, description_en,
        type, value, min_order_amount, usage_limit_per_user,
        is_active, start_date, end_date,
        unlock_condition_type, unlock_condition_config,
        ios_coupon_id, required_membership_level,
        created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
    `;

    const [result] = await pool.execute(insertSql, [
      coupon.code, coupon.title, coupon.englishTitle, coupon.description, coupon.englishDescription,
      coupon.type, coupon.value, coupon.min_order_amount, coupon.usage_limit_per_user,
      coupon.is_active, startDate, endDate,
      coupon.unlock_condition_type, coupon.unlock_condition_config,
      coupon.code, coupon.required_membership_level
    ]);

    const couponId = result.insertId;

    // 创建时间段配置
    if (coupon.timeSlots && coupon.timeSlots.length > 0) {
      await this.insertTimeSlots(couponId, coupon.timeSlots);
    }

    console.log(`✓ 已创建优惠券: ${coupon.code} (${coupon.title})`);
  }

  /**
   * 插入时间段配置
   */
  async insertTimeSlots(couponId, timeSlots) {
    if (!timeSlots || timeSlots.length === 0) return;

    const insertTimeSql = `
      INSERT INTO coupon_time_periods (coupon_id, day_of_week, start_time, end_time)
      VALUES (?, ?, ?, ?)
    `;

    for (const slot of timeSlots) {
      await pool.execute(insertTimeSql, [
        couponId, slot.day_of_week, slot.start_time, slot.end_time
      ]);
    }
  }

  /**
   * 更新时间段配置
   */
  async updateTimeSlots(couponId, timeSlots) {
    // 删除现有时间段
    await pool.execute('DELETE FROM coupon_time_periods WHERE coupon_id = ?', [couponId]);
    
    // 插入新时间段
    await this.insertTimeSlots(couponId, timeSlots);
  }

  /**
   * 显示导入摘要
   */
  displayImportSummary() {
    console.log('\n✅ iOS 礼券配置导入完成！');
    console.log('\n📊 导入摘要:');
    console.log(`   - 新创建: ${this.importedCount} 个优惠券`);
    console.log(`   - 已更新: ${this.updatedCount} 个优惠券`);
    console.log(`   - 跳过: ${this.skippedCount} 个优惠券`);
    console.log(`   - 总处理: ${this.importedCount + this.updatedCount + this.skippedCount} 个优惠券`);
    
    console.log('\n🎯 后续步骤:');
    console.log('   1. 检查后台管理界面中的优惠券列表');
    console.log('   2. 验证时间段限制配置');
    console.log('   3. 测试解锁条件逻辑');
    console.log('   4. 运行 API 测试确保兼容性');
  }
}

// 执行导入
async function main() {
  const importer = new IOSCouponImporter();
  
  try {
    await importer.run();
  } catch (error) {
    console.error('导入执行失败:', error);
    process.exit(1);
  } finally {
    // 关闭数据库连接
    try {
      await pool.end();
    } catch (error) {
      console.warn('关闭数据库连接时出现警告:', error.message);
    }
  }
}

// 如果直接执行此脚本
if (require.main === module) {
  main();
}

module.exports = IOSCouponImporter;